package cn.syc.struck.demo.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;

import cn.syc.struck.demo.App;
import cn.syc.struck.demo.R;
import cn.syc.struck.demo.base.BaseFragment;
import cn.syc.struck.demo.http.entity.gen.MePager;
import cn.syc.struck.demo.http.service.BlogService;
import rx.Subscriber;

/**
 * Created by chenzz on 2017/3/23.
 */

public class ListFragment extends BaseFragment {
    public static final String CLASS_TAG = "LinearFragment";

    private XRecyclerView mRecyclerView;
    private MyAdapter mAdapter;
    private ArrayList<MePager.ListBean> listData;
    private View mEmptyView;

    private TextView textView_text;

    //当前页码
    int curpage = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recyclerview;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {

        mRecyclerView = (XRecyclerView) mRootView.findViewById(R.id.recyclerview);
        textView_text = (TextView) mRootView.findViewById(R.id.textView_text);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mRecyclerView.setLayoutManager(layoutManager);

        //----------add2-------
        mEmptyView = mRootView.findViewById(R.id.include_view_empty);
        mRecyclerView.setEmptyView(mEmptyView);
        //-----------2---------

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey);

        //View header = LayoutInflater.from(getActivity()).inflate(R.layout.recyclerview_header, (ViewGroup) mRootView.findViewById(android.R.id.content), false);
        //mRecyclerView.addHeaderView(header);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                textView_text.setText("正在加载...");
                curpage = 1;
                //BlogService.getInstance().jsonpager(curpage, new PagerSubscriber());

                Subscriber callback = new Subscriber<MePager>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        //TastyToast.makeText(App.getInstance(), e.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR);
                        mRecyclerView.refreshComplete();

                        if (listData.size() > 0) {
                            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        } else {
                            textView_text.setText(e.getMessage());
                        }

                    }

                    @Override
                    public void onNext(MePager t) {


                        if (curpage == 1)
                            listData.clear();

                        if (t.getTotalRow() > 0) {
                            for (MePager.ListBean b : t.getList()) {
                                listData.add(b);
                            }
                            //---------------------------

                            mAdapter.notifyDataSetChanged();
                            //---------------------------

                            mRecyclerView.refreshComplete();
                            if (t.getTotalPage() <= 1)
                                mRecyclerView.setNoMore(true);

                        } else {
                            textView_text.setText("没有数据");
                            mAdapter.notifyDataSetChanged();
                        }


                    }
                };

                BlogService.getInstance().jsonpager(curpage, callback);
            }

            @Override
            public void onLoadMore() {
                //++curpage,加之后再用值，则为第二页开始
                //BlogService.getInstance().jsonpager(++curpage, new PagerSubscriber());

                Subscriber callback = new Subscriber<MePager>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (curpage > 1)
                            mRecyclerView.loadMoreComplete();

                        if (listData.size() > 0) {
                            Toast.makeText(App.getInstance(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        } else {
                            textView_text.setText(e.getMessage());
                        }


                    }

                    @Override
                    public void onNext(MePager t) {
                        if (curpage == 1)
                            listData.clear();

                        if (t.getTotalRow() > 0) {//t.size() > 0
                            for (MePager.ListBean b : t.getList()) {
                                String txt = String.format("%s.%s\r\n%s", b.getName(), b.getEmail(), b.getTime());
                                listData.add(b);
                                //在加载更多时调用下面方法
                                mAdapter.notifyItemInserted(mAdapter.getItemCount());
                            }
                            //---------------------------

                            //mAdapter.notifyDataSetChanged();
                            //---------------------------
                            if (curpage > 1) {
                                // 加载结束务必调用方法refreshComplete,loadMoreComplete,setNoMore
                                // 将XRecyclerView中变量isLoadingData设为false结束加载状态
                                mRecyclerView.loadMoreComplete();
                                if (t.isLastPage())
                                    mRecyclerView.setNoMore(true);
                            } else {
                                mRecyclerView.refreshComplete();
                                if (t.getTotalPage() <= 1)//t.size() < pageSize
                                    mRecyclerView.setNoMore(true);
                            }
                        } else {
                            textView_text.setText("没有数据");
                            mRecyclerView.setNoMore(true);
                            //mAdapter.notifyDataSetChanged();
                        }


                    }
                };

                BlogService.getInstance().jsonpager(++curpage, callback);
            }
        });

        listData = new ArrayList<MePager.ListBean>();
        mAdapter = new MyAdapter(listData);

        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.refresh();

        //========================
        mRootView.findViewById(R.id.button_reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相当于重新下拉刷新
                mRecyclerView.refresh();
                mRecyclerView.refreshComplete();
            }
        });
        //--------------------------
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(CLASS_TAG)}
    )
    public void onHttpError(String txt) {
        //Toast.makeText(LinearActivity.this, "出错:代码为:" + code, Toast.LENGTH_SHORT).show();
        textView_text.setText(txt);
    }

    //-------------------
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public ArrayList<MePager.ListBean> datas = null;

        public MyAdapter(ArrayList<MePager.ListBean> datas) {
            this.datas = datas;
        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            final MePager.ListBean bean = datas.get(position);
            //String txt = String.format("%s\r\n%s", bean.getName(), bean.getTime());
            String txt = String.format("%s\r\n%s\r\n%s", bean.getName(), bean.getEmail(), bean.getTime());
            viewHolder.mTextView.setText(txt);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return datas.size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView mTextView;

            public ViewHolder(View view) {
                super(view);
                mTextView = (TextView) view.findViewById(R.id.text);
            }
            //------------------
        }
    }

    //-------------------

}
